package com.xincheng.shuimalong.activity.sell;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.xincheng.library.util.ClipBoardUtil;
import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.util.UIUtil;
import com.xincheng.library.widget.alertview.AlertView;
import com.xincheng.library.widget.alertview.OnAlertItemClickListener;
import com.xincheng.library.widget.pickerview.OptionsPickerView;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.BaseActivity;
import com.xincheng.shuimalong.activity.OrderDetailActivity;
import com.xincheng.shuimalong.api.AppUrl;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.GetParam;
import com.xincheng.shuimalong.api.PostParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.Constant;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.entity.OrderDetail;
import com.xincheng.shuimalong.entity.config.CommonConfig;
import com.xincheng.shuimalong.entity.config.CompanyLogo;
import com.xincheng.shuimalong.manager.GlideOptionsManager;
import com.xincheng.shuimalong.util.BitmapUtil;
import com.xincheng.shuimalong.util.ConfigUtil;
import com.xincheng.shuimalong.util.GsonUtil;
import com.xincheng.shuimalong.util.ShowActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * Created by xiaote on 2017/7/5.
 * 待回单详情
 */

public class SellReceiptActivity extends BaseActivity {
    @BindView(R.id.order_detail_status_tv)
    TextView mStatusTv;
    @BindView(R.id.order_detail_orderno_tv)
    TextView mOrderNoTv;
    @BindView(R.id.order_detail_updatetime_tv)
    TextView mUpdateTimeTv;
    @BindView(R.id.receipt_pay_money_tv)
    TextView mPayMoneyTv;
    @BindView(R.id.receipt_pay_date_tv)
    TextView mPayDateTv;
    @BindView(R.id.receipt_vci_guarantee_tv)
    TextView mVciGuaranteeTv;
    @BindView(R.id.receipt_tci_guarantee_tv)
    TextView mTciGuaranteeTv;
    @BindView(R.id.receipt_issue_type_tv)
    TextView mIssueTypeTv;
    @BindView(R.id.receipt_express_rg)
    RadioGroup mExpressRg;
    @BindView(R.id.receipt_issue_express_layout)
    LinearLayout mExpressLayout;
    @BindView(R.id.express_choose_tv)
    TextView mExpressChooseTv;
    @BindView(R.id.express_no_et)
    TextView mExpressNoEt;
    //名称 头像 手机号码 保险logo
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.tv_order_name)
    TextView tvOrderName;
    @BindView(R.id.tv_order_phone)
    TextView tvOrderPhone;
    @BindView(R.id.iv_insurance_img)
    ImageView ivInsuranceImg;
    private OrderDetail mOrderDetail;
    private List<CommonConfig> mExpressTypes;
    private List<CommonConfig> mExpressCompanys;
    private OptionsPickerView<CommonConfig> mExpressCompanyPicker;

    private String mToken;
    private int mBidId;
    private long mCreateTime;

    private int mExpressTypeId;
    private int mExpressCompanyId;
    private String mExpressNo = "";

    @Override
    public int getLayoutResId() {
        return R.layout.activity_sell_receipt;
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.order_detail1));
        mToken = PrefUtil.getString(this, PrefKey.TOKEN, "");
        Bundle extras = getIntent().getExtras();
        mBidId = extras.getInt(IntentKey.BID_ID);
        mCreateTime = extras.getLong(IntentKey.CREATE_TIME);
        mExpressTypes = ConfigUtil.getCommonConfigList(this, PrefKey.EXPRESS_TYPE);
        mExpressTypeId = mExpressTypes.get(1).getId();
        mExpressCompanys = ConfigUtil.getCommonConfigList(this, PrefKey.EXPRESS_COMPANYS);
        mOrderNoTv.setText(getString(R.string.order_no, ""));
        tvOrderName.setText(extras.getString(IntentKey.NICK_NAME));
        tvOrderPhone.setText(extras.getString(IntentKey.MOBILE));
        Glide.with(getContext()).load(extras.getString(IntentKey.AVATAR)).apply(GlideOptionsManager.getInstance()
                .getRequestOptions()).into(ivAvatar);
        initPicker();
        getOrderDetail();
    }

    private void initPicker() {
        mExpressCompanyPicker = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                CommonConfig expressCompany = mExpressCompanys.get(options1);
                mExpressCompanyId = expressCompany.getId();
                mExpressChooseTv.setText(expressCompany.getPickerViewText());
            }
        }).setTitleText(getString(R.string.express_choose)).build();
        mExpressCompanyPicker.setPicker(mExpressCompanys);
    }

    @OnClick({R.id.receipt_orderdetail_tv, R.id.express_choose_tv, R.id.receipt_submit_btn,R.id.tv_order_phone})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.receipt_orderdetail_tv://查看订单详情
                if (mOrderDetail != null) {
                    Bundle extras = new Bundle();
                    extras.putInt(IntentKey.FROM, 1);
                    extras.putParcelable(IntentKey.ORDER_DETAIL, mOrderDetail);
                    extras.putLong(IntentKey.CREATE_TIME, mCreateTime);
                    ShowActivity.showActivity(this, OrderDetailActivity.class, extras);
                }
                break;
            case R.id.express_choose_tv://选择快递公司
                if (mExpressCompanyPicker != null) {
                    mExpressCompanyPicker.show();
                }
                break;
            case R.id.receipt_submit_btn://确认回单
                if (checkData()) {
                    mExpressNo = mExpressNoEt.getText().toString().trim();
                    confirmReturn();
                }
                break;
            case R.id.tv_order_phone:
                if (CommonUtil.isEmpty(tvOrderPhone)) {
                    showToast("抱歉，没有联系方式");
                    return;
                }
                String mobile_phone = tvOrderPhone.getText().toString().trim();
                showCallAlert(mobile_phone);
                break;
        }
    }
    private void showCallAlert(final String mobile) {
        new AlertView(this, null, null, getString(R.string.cancel), null, Constant.CALL_WAY,
                AlertView.Style.ActionSheet, new OnAlertItemClickListener() {
            @Override
            public void onItemClick(AlertView alertView, int position) {
                switch (position) {
                    case 0: //呼叫
                        ShowActivity.callPhone(getContext(), mobile);
                        break;
                    case 1: //复制号码
                        ClipBoardUtil.copyText(getContext(), mobile);
                        break;
                    case 2: //添加到通讯录
                        ShowActivity.addContact(getContext(), mobile);
                        break;
                }
            }
        }).show();
    }
    private boolean checkData() {
        if (mExpressTypeId == 2) {
            if (CommonUtil.isEmpty(mExpressChooseTv)) {
                showToast("快递公司不能为空");
                return false;
            }
            if (CommonUtil.isEmpty(mExpressNoEt)) {
                showToast("快递单号不能为空");
                return false;
            }
            if(mExpressNoEt.length() > 20) {
                showToast("快递单号最长20位");
                return false;
            }
        }
        return true;
    }

    @Override
    public void addListener() {
        mExpressRg.setOnCheckedChangeListener(new MyOnCheckedChangedListener());
    }

    private void getOrderDetail() {
        RetroSubscrube.getInstance().getSubscrube(GetParam.viewBillOrder(mToken, mBidId),
                new BaseObserver(this, getString(R.string.loading_data)) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        if (data != null) {
                            mOrderDetail = GsonUtil.parseData(data, OrderDetail.class);
                            parseDetail();
                        }
                    }
                });
    }

    private void parseDetail() {
        mStatusTv.setText("待回单");
        mOrderNoTv.setText(getString(R.string.order_no, mOrderDetail.getOrderNo()));
        mUpdateTimeTv.setText(mOrderDetail.getUpdateTime());
        mPayMoneyTv.setText(getString(R.string.money_value, mOrderDetail.getTotalMoney()));
        mPayDateTv.setText(mOrderDetail.getPayTime());
        mVciGuaranteeTv.setText(mOrderDetail.getVciNo());
        mTciGuaranteeTv.setText(mOrderDetail.getTciNo());
        mIssueTypeTv.setText(mOrderDetail.getShippingMsg());
        CompanyLogo companyLogo = ConfigUtil.getCompanyLogoById(this,mOrderDetail.getCompanyId());
        final int screenWith = UIUtil.getDisplaySize(this)[0];
        if (companyLogo != null) {
            Glide.with(this).asBitmap().load(companyLogo.getLogo()).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    Bitmap bitmap = BitmapUtil.zoomImg(resource, screenWith / 3);
                    ivInsuranceImg.setImageBitmap(bitmap);
                }
            });
        }
    }

    private void confirmReturn() {
        RetroSubscrube.getInstance().postSubscrube(AppUrl.CONFRIM_RETURN,
                PostParam.confirmReturn(mToken, mBidId, mExpressTypeId, mExpressCompanyId, mExpressNo),
                new BaseObserver(this, getString(R.string.loading_submit)) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        showToast("提交成功");
                        Intent intent = new Intent();
                        intent.putExtra(IntentKey.SIGN_RECEIVE_SUCCESS, true);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });
    }

    private class MyOnCheckedChangedListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup radioGroup, @IdRes int checkId) {
            switch (checkId) {
                case R.id.receipt_express_toface_rb:
                    mExpressTypeId = mExpressTypes.get(0).getId();
                    mExpressLayout.setVisibility(View.GONE);
                    break;
                case R.id.receipt_express_mail_rb:
                    mExpressTypeId = mExpressTypes.get(1).getId();
                    mExpressLayout.setVisibility(View.VISIBLE);
                    break;
            }
        }
    }
}
